using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// UI管理器。
/// </summary>
public class UIManager : Singleton<UIManager>
{

    private const int DefaultDepth = 0;
    private const int DepthInterval = 10;

    private Transform m_InstanceRoot = null;
    private readonly Dictionary<string, UIGroup> m_UIGroups = new Dictionary<string, UIGroup>();
    private readonly Dictionary<int, IUIForm> m_UIForms = new Dictionary<int, IUIForm>();
    private readonly List<IUIForm> m_RecycleQueue = new List<IUIForm>();
    private int m_SerialId = 0;
    private int m_UIFormId = 0;

    [SerializeField]
    private string m_InstanceRootName = "UI Instance Root";

    [SerializeField]
    private int m_InstancePoolCapacity = 16;

    public override void Awake()
    {
        base.Awake();
        // 确保在游戏启动时初始化UI层级
        if (m_InstanceRoot == null)
        {
            Initialize();
        }
    }

    private void Start()
    {
        // 在Start中再次确保UI层级已创建（防止某些情况下Awake未执行）
        if (m_InstanceRoot == null || m_UIGroups.Count == 0)
        {
            Initialize();
        }
    }

    private void Update()
    {
        while (m_RecycleQueue.Count > 0)
        {
            IUIForm uiForm = m_RecycleQueue[0];
            m_RecycleQueue.RemoveAt(0);
            uiForm.OnRecycle();
            Object.Destroy((uiForm.Handle as MonoBehaviour).gameObject);
        }
    }

    /// <summary>
    /// 初始化UI管理器（创建UI层级结构）。
    /// </summary>
    public void Initialize()
    {
        if (m_InstanceRoot == null)
        {
            // 查找Canvas，优先查找GameApp下的Canvas
            Transform canvasTransform = null;
            GameObject gameAppObj = GameObject.Find("GameApp");
            if (gameAppObj != null)
            {
                canvasTransform = gameAppObj.transform.Find("Canvas");
            }
            
            // 如果没找到，尝试通过FindObjectOfType查找
            if (canvasTransform == null)
            {
                Canvas canvas = Object.FindObjectOfType<Canvas>();
                if (canvas != null)
                {
                    canvasTransform = canvas.transform;
                }
            }
            
            // 如果还是没找到，创建一个Canvas
            if (canvasTransform == null)
            {
                GameObject canvasObject = new GameObject("Canvas");
                Canvas canvas = canvasObject.AddComponent<Canvas>();
                canvas.renderMode = RenderMode.ScreenSpaceOverlay;
                canvasObject.AddComponent<UnityEngine.UI.CanvasScaler>();
                canvasObject.AddComponent<UnityEngine.UI.GraphicRaycaster>();
                canvasTransform = canvasObject.transform;
                
                // 如果GameApp存在，将Canvas设置为GameApp的子节点
                if (gameAppObj != null)
                {
                    canvasTransform.SetParent(gameAppObj.transform);
                }
            }

            // 创建UI根节点（先检查Canvas下是否已存在）
            Transform existingRoot = canvasTransform.Find(m_InstanceRootName);
            GameObject rootObject = null;
            if (existingRoot != null)
            {
                rootObject = existingRoot.gameObject;
            }
            else
            {
                rootObject = new GameObject(m_InstanceRootName);
            }
            m_InstanceRoot = rootObject.transform;
            
            // 确保父节点正确
            if (m_InstanceRoot.parent != canvasTransform)
            {
                m_InstanceRoot.SetParent(canvasTransform);
            }
            
            m_InstanceRoot.localPosition = Vector3.zero;
            m_InstanceRoot.localRotation = Quaternion.identity;
            m_InstanceRoot.localScale = Vector3.one;

            // 为根节点添加RectTransform（如果需要）
            RectTransform rootRectTransform = rootObject.GetOrAddComponent<RectTransform>();
            if (rootRectTransform != null)
            {
                rootRectTransform.anchorMin = Vector2.zero;
                rootRectTransform.anchorMax = Vector2.one;
                rootRectTransform.anchoredPosition = Vector2.zero;
                rootRectTransform.sizeDelta = Vector2.zero;
            }

            // 确保有EventSystem（UI交互需要）
            EnsureEventSystem();
        }

        // 创建默认UI组
        AddUIGroup(Config.UIGroup.Page, 0);
        AddUIGroup(Config.UIGroup.Main, 10);
        AddUIGroup(Config.UIGroup.Form, 20);
        AddUIGroup(Config.UIGroup.Dialog, 30);
        AddUIGroup(Config.UIGroup.Mask, 40);
        AddUIGroup(Config.UIGroup.Tip, 50);
    }

    /// <summary>
    /// 确保场景中有EventSystem（UI交互需要）。
    /// </summary>
    private void EnsureEventSystem()
    {
        if (UnityEngine.EventSystems.EventSystem.current == null)
        {
            GameObject eventSystemObject = new GameObject("EventSystem");
            eventSystemObject.AddComponent<UnityEngine.EventSystems.EventSystem>();
            eventSystemObject.AddComponent<UnityEngine.EventSystems.StandaloneInputModule>();
            eventSystemObject.transform.SetParent(transform);
        }
    }

    /// <summary>
    /// 添加UI组。
    /// </summary>
    /// <param name="uiGroupName">UI组名称。</param>
    /// <param name="depth">UI组深度。</param>
    /// <returns>是否添加UI组成功。</returns>
    public bool AddUIGroup(string uiGroupName, int depth)
    {
        if (string.IsNullOrEmpty(uiGroupName))
        {
            Logger.LogError("UI group name is invalid.");
            return false;
        }

        if (HasUIGroup(uiGroupName))
        {
            return false;
        }

        UIGroup uiGroup = CreateUIGroup(uiGroupName, depth);
        if (uiGroup == null)
        {
            Logger.LogErrorFormat("Can not create UI group '{0}'.", uiGroupName);
            return false;
        }

        m_UIGroups.Add(uiGroupName, uiGroup);
        return true;
    }

    /// <summary>
    /// 是否存在UI组。
    /// </summary>
    /// <param name="uiGroupName">UI组名称。</param>
    /// <returns>是否存在UI组。</returns>
    public bool HasUIGroup(string uiGroupName)
    {
        if (string.IsNullOrEmpty(uiGroupName))
        {
            return false;
        }

        return m_UIGroups.ContainsKey(uiGroupName);
    }

    /// <summary>
    /// 获取UI组。
    /// </summary>
    /// <param name="uiGroupName">UI组名称。</param>
    /// <returns>要获取的UI组。</returns>
    public IUIGroup GetUIGroup(string uiGroupName)
    {
        if (string.IsNullOrEmpty(uiGroupName))
        {
            return null;
        }

        if (m_UIGroups.TryGetValue(uiGroupName, out UIGroup uiGroup))
        {
            return uiGroup;
        }

        return null;
    }

    /// <summary>
    /// 获取所有UI组。
    /// </summary>
    /// <returns>所有UI组。</returns>
    public IUIGroup[] GetAllUIGroups()
    {
        int index = 0;
        IUIGroup[] results = new IUIGroup[m_UIGroups.Count];
        foreach (KeyValuePair<string, UIGroup> uiGroup in m_UIGroups)
        {
            results[index++] = uiGroup.Value;
        }

        return results;
    }

    /// <summary>
    /// 预加载UI界面（不显示，仅加载资源）。
    /// </summary>
    /// <param name="uiFormAssetName">界面资源名称。</param>
    /// <param name="uiGroupName">界面组名称。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>界面序列编号，0表示失败。</returns>
    public int PreloadUIForm(string uiFormAssetName, string uiGroupName, object userData = null)
    {
        if (string.IsNullOrEmpty(uiFormAssetName))
        {
            Logger.LogError("UI form asset name is invalid.");
            return 0;
        }

        if (string.IsNullOrEmpty(uiGroupName))
        {
            Logger.LogError("UI group name is invalid.");
            return 0;
        }

        IUIGroup uiGroup = GetUIGroup(uiGroupName);
        if (uiGroup == null)
        {
            Logger.LogErrorFormat("UI group '{0}' is not exist.", uiGroupName);
            return 0;
        }

        // 加载UI预制体
        GameObject uiFormAsset = Resources.Load<GameObject>(uiFormAssetName);
        if (uiFormAsset == null)
        {
            Logger.LogErrorFormat("Can not load UI form from '{0}'.", uiFormAssetName);
            return 0;
        }

        // 实例化UI（但不显示）
        GameObject uiFormInstance = Object.Instantiate(uiFormAsset);
        Transform uiGroupTransform = (uiGroup.Helper as MonoBehaviour).transform;
        uiFormInstance.transform.SetParent(uiGroupTransform, false);
        uiFormInstance.SetActive(false); // 预加载时不显示

        // 获取UIForm组件
        UIForm uiForm = uiFormInstance.GetOrAddComponent<UIForm>();
        if (uiForm == null)
        {
            Logger.LogErrorFormat("UI form '{0}' can not get UI form component.", uiFormAssetName);
            Object.Destroy(uiFormInstance);
            return 0;
        }

        int serialId = ++m_SerialId;
        // 预加载时使用自增ID
        int autoFormId = ++m_UIFormId;
        uiForm.SetUIFormId(autoFormId);

        // 初始化UIForm
        uiForm.OnInit(serialId, uiFormAssetName, uiGroup, true, true, userData);

        // 添加到UI组
        UIGroup group = uiGroup as UIGroup;
        if (group != null)
        {
            group.AddUIForm(uiForm);
        }

        // 建立界面导航链表关系
        BuildUIFormNavigation(uiForm);

        // 添加到管理器
        m_UIForms.Add(serialId, uiForm);

        // 调用预加载方法
        uiForm.OnPreload(userData);

        return serialId;
    }

    /// <summary>
    /// 通过界面ID打开UI界面。
    /// </summary>
    /// <param name="uiFormId">界面ID。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>界面序列编号，失败返回0。</returns>
    public int OpenUIForm(int uiFormId, object userData = null)
    {
        if (uiFormId <= 0)
        {
            Logger.LogError("UI form ID is invalid.");
            return 0;
        }

        Config.UIFormInfo info = Config.UIForm.GetUIFormInfo(uiFormId);
        if (info == null)
        {
            Logger.LogErrorFormat("UI form ID '{0}' is not registered.", uiFormId);
            return 0;
        }

        // 检查界面是否已经打开
        IUIForm existingForm = GetUIFormById(uiFormId);
        if (existingForm != null)
        {
            Logger.LogWarningFormat("UI form with ID '{0}' (AssetName: '{1}') is already open. SerialId: {2}. Opening request ignored.", 
                uiFormId, existingForm.UIFormAssetName, existingForm.SerialId);
            return 0;
        }

        // 打开界面并传入UIFormId
        return OpenUIForm(info.AssetName, info.UIGroupName, info.PauseCoveredUIForm, userData, uiFormId);
    }

    /// <summary>
    /// 打开UI界面。
    /// </summary>
    /// <param name="uiFormAssetName">界面资源名称。</param>
    /// <param name="uiGroupName">界面组名称。</param>
    /// <param name="pauseCoveredUIForm">是否暂停被覆盖的界面。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <param name="uiFormId">界面ID（可选，用于通过UIFormId打开时）。</param>
    /// <returns>界面序列编号。</returns>
    public int OpenUIForm(string uiFormAssetName, string uiGroupName, bool pauseCoveredUIForm = true, object userData = null, int uiFormId = 0)
    {
        if (string.IsNullOrEmpty(uiFormAssetName))
        {
            Logger.LogError("UI form asset name is invalid.");
            return 0;
        }

        if (string.IsNullOrEmpty(uiGroupName))
        {
            Logger.LogError("UI group name is invalid.");
            return 0;
        }

        // 如果传入了uiFormId，检查界面是否已经打开
        if (uiFormId > 0)
        {
            IUIForm existingForm = GetUIFormById(uiFormId);
            if (existingForm != null)
            {
                Logger.LogWarningFormat("UI form with ID '{0}' (AssetName: '{1}') is already open. SerialId: {2}. Opening request ignored.", 
                    uiFormId, existingForm.UIFormAssetName, existingForm.SerialId);
                return 0;
            }
        }
        else
        {
            // 如果没有传入uiFormId，通过资源名称检查是否已经打开
            IUIForm existingForm = GetUIForm(uiFormAssetName, uiGroupName);
            if (existingForm != null)
            {
                Logger.LogWarningFormat("UI form with AssetName '{0}' in UIGroup '{1}' is already open. SerialId: {2}. Opening request ignored.", 
                    uiFormAssetName, uiGroupName, existingForm.SerialId);
                return 0;
            }
        }

        IUIGroup uiGroup = GetUIGroup(uiGroupName);
        if (uiGroup == null)
        {
            Logger.LogErrorFormat("UI group '{0}' is not exist.", uiGroupName);
            return 0;
        }

        // 加载UI预制体
        GameObject uiFormAsset = Resources.Load<GameObject>(uiFormAssetName);
        if (uiFormAsset == null)
        {
            Logger.LogErrorFormat("Can not load UI form from '{0}'.", uiFormAssetName);
            return 0;
        }

        // 实例化UI
        GameObject uiFormInstance = Object.Instantiate(uiFormAsset);
        Transform uiGroupTransform = (uiGroup.Helper as MonoBehaviour).transform;
        uiFormInstance.transform.SetParent(uiGroupTransform, false);

        // 获取UIForm组件
        UIForm uiForm = uiFormInstance.GetOrAddComponent<UIForm>();
        if (uiForm == null)
        {
            Logger.LogErrorFormat("UI form '{0}' can not get UI form component.", uiFormAssetName);
            Object.Destroy(uiFormInstance);
            return 0;
        }

        int serialId = ++m_SerialId;
        // 如果传入了uiFormId，使用传入的ID，否则使用自增ID
        if (uiFormId > 0)
        {
            uiForm.SetUIFormId(uiFormId);
        }
        else
        {
            int autoFormId = ++m_UIFormId;
            uiForm.SetUIFormId(autoFormId);
        }

        // 初始化UIForm
        uiForm.OnInit(serialId, uiFormAssetName, uiGroup, pauseCoveredUIForm, true, userData);

        // 添加到UI组
        UIGroup group = uiGroup as UIGroup;
        if (group != null)
        {
            group.AddUIForm(uiForm);
        }

        // 建立界面导航链表关系
        BuildUIFormNavigation(uiForm);

        // 添加到管理器
        m_UIForms.Add(serialId, uiForm);

        // 打开UI
        uiForm.OnOpen(userData);

        // 自动加载子界面（递归加载）
        LoadSubUIForms(uiForm, userData);

        return serialId;
    }

    /// <summary>
    /// 通过界面ID关闭UI界面。
    /// </summary>
    /// <param name="uiFormId">界面ID。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否关闭UI界面成功。</returns>
    public bool CloseUIFormById(int uiFormId, object userData = null)
    {
        if (uiFormId <= 0)
        {
            Logger.LogWarningFormat("Close UI form failed: UI form ID '{0}' is invalid.", uiFormId);
            return false;
        }

        IUIForm uiForm = GetUIFormById(uiFormId);
        if (uiForm == null)
        {
            Logger.LogWarningFormat("Close UI form failed: UI form with ID '{0}' is not found or already closed.", uiFormId);
            return false;
        }

        CloseUIForm(uiForm, false, userData);
        return true;
    }

    /// <summary>
    /// 关闭UI界面。
    /// </summary>
    /// <param name="serialId">界面序列编号。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否关闭UI界面成功。</returns>
    public bool CloseUIForm(int serialId, object userData = null)
    {
        return CloseUIForm(serialId, false, userData);
    }

    /// <summary>
    /// 关闭UI界面。
    /// </summary>
    /// <param name="serialId">界面序列编号。</param>
    /// <param name="isShutdown">是否是关闭UI管理器时触发。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否关闭UI界面成功。</returns>
    public bool CloseUIForm(int serialId, bool isShutdown, object userData = null)
    {
        if (serialId <= 0)
        {
            Logger.LogWarningFormat("Close UI form failed: SerialId '{0}' is invalid.", serialId);
            return false;
        }

        IUIForm uiForm = GetUIForm(serialId);
        if (uiForm == null)
        {
            Logger.LogWarningFormat("Close UI form failed: UI form with SerialId '{0}' is not found or already closed.", serialId);
            return false;
        }

        CloseUIForm(uiForm, isShutdown, userData);
        return true;
    }

    /// <summary>
    /// 关闭UI界面。
    /// </summary>
    /// <param name="uiForm">要关闭的界面。</param>
    /// <param name="isShutdown">是否是关闭UI管理器时触发。</param>
    /// <param name="userData">用户自定义数据。</param>
    public void CloseUIForm(IUIForm uiForm, bool isShutdown, object userData = null)
    {
        if (uiForm == null)
        {
            Logger.LogWarning("Close UI form failed: UI form is null.");
            return;
        }

        IUIGroup uiGroup = uiForm.UIGroup;
        if (uiGroup == null)
        {
            Logger.LogError("UI group is invalid.");
            return;
        }

        // 更新界面导航链表关系
        UpdateUIFormNavigation(uiForm);

        // 从UI组移除
        UIGroup group = uiGroup as UIGroup;
        if (group != null)
        {
            group.RemoveUIForm(uiForm);
            // 刷新UI组
            group.Refresh();
        }

        // 关闭所有子界面（递归关闭）
        CloseSubUIForms(uiForm, isShutdown, userData);

        // 从管理器移除
        m_UIForms.Remove(uiForm.SerialId);

        // 关闭UI
        uiForm.OnClose(isShutdown, userData);

        // 加入回收队列
        m_RecycleQueue.Add(uiForm);
    }

    /// <summary>
    /// 激活UI界面。
    /// </summary>
    /// <param name="serialId">界面序列编号。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否激活UI界面成功。</returns>
    public bool RefocusUIForm(int serialId, object userData = null)
    {
        IUIForm uiForm = GetUIForm(serialId);
        if (uiForm == null)
        {
            return false;
        }

        return RefocusUIForm(uiForm, userData);
    }

    /// <summary>
    /// 激活UI界面。
    /// </summary>
    /// <param name="uiForm">要激活的界面。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否激活UI界面成功。</returns>
    public bool RefocusUIForm(IUIForm uiForm, object userData = null)
    {
        if (uiForm == null)
        {
            return false;
        }

        IUIGroup uiGroup = uiForm.UIGroup;
        if (uiGroup == null)
        {
            return false;
        }

        // 将界面移到UI组顶部
        UIGroup group = uiGroup as UIGroup;
        if (group != null)
        {
            group.RefocusUIForm(uiForm);
        }

        uiForm.OnRefocus(userData);
        return true;
    }

    /// <summary>
    /// 获取UI界面。
    /// </summary>
    /// <param name="serialId">界面序列编号。</param>
    /// <returns>要获取的界面。</returns>
    public IUIForm GetUIForm(int serialId)
    {
        if (serialId <= 0)
        {
            return null;
        }

        if (m_UIForms.TryGetValue(serialId, out IUIForm uiForm))
        {
            return uiForm;
        }

        return null;
    }

    /// <summary>
    /// 获取UI界面。
    /// </summary>
    /// <param name="uiFormAssetName">界面资源名称。</param>
    /// <returns>要获取的界面。</returns>
    public IUIForm GetUIForm(string uiFormAssetName)
    {
        if (string.IsNullOrEmpty(uiFormAssetName))
        {
            return null;
        }

        foreach (KeyValuePair<int, IUIForm> uiForm in m_UIForms)
        {
            if (uiForm.Value.UIFormAssetName == uiFormAssetName)
            {
                return uiForm.Value;
            }
        }

        return null;
    }

    /// <summary>
    /// 获取UI界面。
    /// </summary>
    /// <param name="uiFormId">界面ID。</param>
    /// <returns>要获取的界面。</returns>
    public IUIForm GetUIFormById(int uiFormId)
    {
        if (uiFormId <= 0)
        {
            return null;
        }

        foreach (KeyValuePair<int, IUIForm> uiForm in m_UIForms)
        {
            UIForm form = uiForm.Value as UIForm;
            if (form != null && form.UIFormId == uiFormId)
            {
                return uiForm.Value;
            }
        }

        return null;
    }

    /// <summary>
    /// 获取UI界面。
    /// </summary>
    /// <param name="uiFormAssetName">界面资源名称。</param>
    /// <param name="uiGroupName">界面组名称。</param>
    /// <returns>要获取的界面。</returns>
    public IUIForm GetUIForm(string uiFormAssetName, string uiGroupName)
    {
        IUIGroup uiGroup = GetUIGroup(uiGroupName);
        if (uiGroup == null)
        {
            return null;
        }

        return uiGroup.GetUIForm(uiFormAssetName);
    }

    /// <summary>
    /// 创建UI组。
    /// </summary>
    /// <param name="uiGroupName">UI组名称。</param>
    /// <param name="depth">UI组深度。</param>
    /// <returns>创建的UI组。</returns>
    private UIGroup CreateUIGroup(string uiGroupName, int depth)
    {
        // 确保实例根节点已创建（不应该在这里创建，应该由Initialize()创建）
        if (m_InstanceRoot == null)
        {
            // 先尝试查找Canvas下的 UI Instance Root
            Transform canvasTransform = null;
            GameObject gameAppObj = GameObject.Find("GameApp");
            if (gameAppObj != null)
            {
                canvasTransform = gameAppObj.transform.Find("Canvas");
            }
            
            if (canvasTransform == null)
            {
                Canvas canvas = Object.FindObjectOfType<Canvas>();
                if (canvas != null)
                {
                    canvasTransform = canvas.transform;
                }
            }
            
            if (canvasTransform != null)
            {
                Transform existingRoot = canvasTransform.Find(m_InstanceRootName);
                if (existingRoot != null)
                {
                    m_InstanceRoot = existingRoot;
                }
            }
            
            // 如果仍然找不到，调用Initialize()来创建
            if (m_InstanceRoot == null)
            {
                Initialize();
            }
        }

        // 如果仍然为null，说明Initialize()也失败了，无法创建UI Group
        if (m_InstanceRoot == null)
        {
            Logger.LogErrorFormat("Can not create UI group '{0}' because UI Instance Root is not initialized.", uiGroupName);
            return null;
        }

        // 创建UI组根节点
        string uiGroupHelperName = string.Format("UI Group - {0}", uiGroupName);
        GameObject uiGroupHelperObject = new GameObject(uiGroupHelperName);
        
        // 确保有RectTransform组件
        RectTransform rectTransform = uiGroupHelperObject.GetOrAddComponent<RectTransform>();
        if (rectTransform == null)
        {
            Logger.LogErrorFormat("Can not create RectTransform for UI group '{0}'.", uiGroupName);
            Object.Destroy(uiGroupHelperObject);
            return null;
        }

        // 设置父节点
        rectTransform.SetParent(m_InstanceRoot, false);
        
        // 设置RectTransform属性（全屏）
        rectTransform.anchorMin = Vector2.zero;
        rectTransform.anchorMax = Vector2.one;
        rectTransform.anchoredPosition = Vector2.zero;
        rectTransform.sizeDelta = Vector2.zero;
        rectTransform.localPosition = Vector3.zero;
        rectTransform.localRotation = Quaternion.identity;
        rectTransform.localScale = Vector3.one;

        // 添加UIGroupHelper组件
        UIGroupHelper uiGroupHelper = uiGroupHelperObject.GetOrAddComponent<UIGroupHelper>();
        if (uiGroupHelper == null)
        {
            Logger.LogErrorFormat("Can not create UI group helper for UI group '{0}'.", uiGroupName);
            Object.Destroy(uiGroupHelperObject);
            return null;
        }

        // 添加UIGroup组件
        UIGroup uiGroup = uiGroupHelperObject.GetOrAddComponent<UIGroup>();
        if (uiGroup == null)
        {
            Logger.LogErrorFormat("Can not create UI group for UI group '{0}'.", uiGroupName);
            Object.Destroy(uiGroupHelperObject);
            return null;
        }

        // 初始化UI组
        uiGroup.Initialize(uiGroupName, depth, uiGroupHelper);
        
        return uiGroup;
    }

    #region 界面导航链表管理

    /// <summary>
    /// 建立界面导航链表关系。
    /// </summary>
    /// <param name="uiForm">当前界面。</param>
    private void BuildUIFormNavigation(IUIForm uiForm)
    {
        if (uiForm == null)
        {
            return;
        }

        UIForm currentForm = uiForm as UIForm;
        if (currentForm == null)
        {
            return;
        }

        // 查找当前UI组中最后一个界面作为前一个界面
        IUIGroup uiGroup = uiForm.UIGroup;
        if (uiGroup != null)
        {
            IUIForm[] allForms = uiGroup.GetAllUIForms();
            if (allForms != null && allForms.Length > 0)
            {
                // 找到当前界面之前最后打开的界面（排除当前界面本身）
                for (int i = allForms.Length - 1; i >= 0; i--)
                {
                    IUIForm previousForm = allForms[i];
                    if (previousForm != null && previousForm != uiForm)
                    {
                        UIForm prevForm = previousForm as UIForm;
                        if (prevForm != null)
                        {
                            // 建立双向链表关系
                            currentForm.PreviousUIForm = previousForm;
                            prevForm.NextUIForm = uiForm;
                            break;
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// 更新界面导航链表关系（关闭界面时调用）。
    /// </summary>
    /// <param name="uiForm">要关闭的界面。</param>
    private void UpdateUIFormNavigation(IUIForm uiForm)
    {
        if (uiForm == null)
        {
            return;
        }

        UIForm currentForm = uiForm as UIForm;
        if (currentForm == null)
        {
            return;
        }

        IUIForm previousForm = currentForm.PreviousUIForm;
        IUIForm nextForm = currentForm.NextUIForm;

        // 更新链表关系
        if (previousForm != null)
        {
            UIForm prevForm = previousForm as UIForm;
            if (prevForm != null)
            {
                prevForm.NextUIForm = nextForm;
            }
        }

        if (nextForm != null)
        {
            UIForm nextFormObj = nextForm as UIForm;
            if (nextFormObj != null)
            {
                nextFormObj.PreviousUIForm = previousForm;
            }
        }

        // 清除当前界面的链表关系
        currentForm.PreviousUIForm = null;
        currentForm.NextUIForm = null;
    }

    /// <summary>
    /// 返回前一个界面。
    /// </summary>
    /// <param name="serialId">当前界面序列编号。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否成功返回前一个界面。</returns>
    public bool GoBackToPreviousUIForm(int serialId, object userData = null)
    {
        IUIForm currentForm = GetUIForm(serialId);
        if (currentForm == null)
        {
            return false;
        }

        return GoBackToPreviousUIForm(currentForm, userData);
    }

    /// <summary>
    /// 返回前一个界面。
    /// </summary>
    /// <param name="currentForm">当前界面。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否成功返回前一个界面。</returns>
    public bool GoBackToPreviousUIForm(IUIForm currentForm, object userData = null)
    {
        if (currentForm == null)
        {
            return false;
        }

        UIForm form = currentForm as UIForm;
        if (form == null)
        {
            return false;
        }

        IUIForm previousForm = form.PreviousUIForm;
        if (previousForm == null)
        {
            Logger.LogWarning("No previous UI form to go back to.");
            return false;
        }

        // 关闭当前界面
        CloseUIForm(currentForm, false, userData);

        // 显示前一个界面
        if (previousForm.Handle is MonoBehaviour)
        {
            MonoBehaviour prevMono = previousForm.Handle as MonoBehaviour;
            if (prevMono != null && prevMono.gameObject != null)
            {
                // 如果前一个界面被隐藏了，重新显示它
                if (!prevMono.gameObject.activeSelf)
                {
                    prevMono.gameObject.SetActive(true);
                }

                // 激活前一个界面
                RefocusUIForm(previousForm, userData);
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// 获取前一个界面。
    /// </summary>
    /// <param name="serialId">当前界面序列编号。</param>
    /// <returns>前一个界面，如果没有则返回null。</returns>
    public IUIForm GetPreviousUIForm(int serialId)
    {
        IUIForm currentForm = GetUIForm(serialId);
        if (currentForm == null)
        {
            return null;
        }

        UIForm form = currentForm as UIForm;
        if (form == null)
        {
            return null;
        }

        return form.PreviousUIForm;
    }

    /// <summary>
    /// 获取下一个界面。
    /// </summary>
    /// <param name="serialId">当前界面序列编号。</param>
    /// <returns>下一个界面，如果没有则返回null。</returns>
    public IUIForm GetNextUIForm(int serialId)
    {
        IUIForm currentForm = GetUIForm(serialId);
        if (currentForm == null)
        {
            return null;
        }

        UIForm form = currentForm as UIForm;
        if (form == null)
        {
            return null;
        }

        return form.NextUIForm;
    }

    #endregion

    #region 子界面管理

    /// <summary>
    /// 加载子界面（递归加载）。
    /// </summary>
    /// <param name="parentUIForm">父界面。</param>
    /// <param name="userData">用户自定义数据。</param>
    private void LoadSubUIForms(IUIForm parentUIForm, object userData = null)
    {
        if (parentUIForm == null)
        {
            return;
        }

        UIForm parentForm = parentUIForm as UIForm;
        if (parentForm == null)
        {
            return;
        }

        // 获取父界面的配置信息
        int parentUIFormId = parentForm.UIFormId;
        if (parentUIFormId <= 0)
        {
            return;
        }

        Config.UIFormInfo parentInfo = Config.UIForm.GetUIFormInfo(parentUIFormId);
        if (parentInfo == null || parentInfo.SubUIFormIds == null || parentInfo.SubUIFormIds.Count == 0)
        {
            return;
        }

        // 遍历子界面ID列表，递归加载
        foreach (int subUIFormId in parentInfo.SubUIFormIds)
        {
            if (subUIFormId <= 0)
            {
                continue;
            }

            // 打开子界面（会自动递归加载子界面的子界面）
            int subSerialId = OpenUIForm(subUIFormId, userData);
            if (subSerialId > 0)
            {
                IUIForm subUIForm = GetUIForm(subSerialId);
                if (subUIForm != null)
                {
                    // 建立父子关系
                    parentForm.AddSubUIForm(subUIForm);
                }
            }
        }
    }

    /// <summary>
    /// 关闭所有子界面（递归关闭）。
    /// </summary>
    /// <param name="parentUIForm">父界面。</param>
    /// <param name="isShutdown">是否是关闭UI管理器时触发。</param>
    /// <param name="userData">用户自定义数据。</param>
    private void CloseSubUIForms(IUIForm parentUIForm, bool isShutdown, object userData = null)
    {
        if (parentUIForm == null)
        {
            return;
        }

        UIForm parentForm = parentUIForm as UIForm;
        if (parentForm == null)
        {
            return;
        }

        // 获取所有子界面
        IUIForm[] subUIForms = parentForm.SubUIForms;
        if (subUIForms == null || subUIForms.Length == 0)
        {
            return;
        }

        // 递归关闭所有子界面
        foreach (IUIForm subUIForm in subUIForms)
        {
            if (subUIForm != null)
            {
                // 递归关闭子界面的子界面
                CloseSubUIForms(subUIForm, isShutdown, userData);

                // 关闭子界面
                CloseUIForm(subUIForm, isShutdown, userData);
            }
        }

        // 清除父子关系
        parentForm.ClearSubUIForms();
    }

    /// <summary>
    /// 打开子界面（显示）。
    /// </summary>
    /// <param name="parentUIFormId">父界面ID。</param>
    /// <param name="subUIFormId">子界面ID。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否成功打开子界面。</returns>
    public bool OpenSubUIForm(int parentUIFormId, int subUIFormId, object userData = null)
    {
        if (parentUIFormId <= 0)
        {
            Logger.LogWarningFormat("Open sub UI form failed: Parent UI form ID '{0}' is invalid.", parentUIFormId);
            return false;
        }

        if (subUIFormId <= 0)
        {
            Logger.LogWarningFormat("Open sub UI form failed: Sub UI form ID '{0}' is invalid.", subUIFormId);
            return false;
        }

        IUIForm parentForm = GetUIFormById(parentUIFormId);
        if (parentForm == null)
        {
            Logger.LogWarningFormat("Open sub UI form failed: Parent UI form with ID '{0}' is not found.", parentUIFormId);
            return false;
        }

        return OpenSubUIForm(parentForm, subUIFormId, userData);
    }

    /// <summary>
    /// 打开子界面（显示）。
    /// </summary>
    /// <param name="parentUIForm">父界面。</param>
    /// <param name="subUIFormId">子界面ID。</param>
    /// <param name="userData">用户自定义数据。</param>
    /// <returns>是否成功打开子界面。</returns>
    public bool OpenSubUIForm(IUIForm parentUIForm, int subUIFormId, object userData = null)
    {
        if (parentUIForm == null)
        {
            Logger.LogWarning("Open sub UI form failed: Parent UI form is null.");
            return false;
        }

        if (subUIFormId <= 0)
        {
            Logger.LogWarningFormat("Open sub UI form failed: Sub UI form ID '{0}' is invalid.", subUIFormId);
            return false;
        }

        UIForm parentForm = parentUIForm as UIForm;
        if (parentForm == null)
        {
            Logger.LogWarning("Open sub UI form failed: Parent UI form is not a valid UIForm instance.");
            return false;
        }

        // 检查子界面是否已经存在
        IUIForm[] existingSubForms = parentForm.SubUIForms;
        foreach (IUIForm subForm in existingSubForms)
        {
            UIForm form = subForm as UIForm;
            if (form != null && form.UIFormId == subUIFormId)
            {
                // 子界面已存在，显示它
                UIFormLogic logic = form.Logic;
                if (logic != null)
                {
                    logic.Visible = true;
                    logic.OnResume();
                    return true;
                }
            }
        }

        // 子界面不存在，需要创建
        Config.UIFormInfo subInfo = Config.UIForm.GetUIFormInfo(subUIFormId);
        if (subInfo == null)
        {
            Logger.LogWarningFormat("Open sub UI form failed: Sub UI form ID '{0}' is not registered.", subUIFormId);
            return false;
        }

        // 打开子界面
        int subSerialId = OpenUIForm(subInfo.AssetName, subInfo.UIGroupName, subInfo.PauseCoveredUIForm, userData, subUIFormId);
        if (subSerialId > 0)
        {
            IUIForm subUIForm = GetUIForm(subSerialId);
            if (subUIForm != null)
            {
                // 建立父子关系
                parentForm.AddSubUIForm(subUIForm);
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// 隐藏子界面（不销毁，只是隐藏）。
    /// </summary>
    /// <param name="parentUIFormId">父界面ID。</param>
    /// <param name="subUIFormId">子界面ID。</param>
    /// <returns>是否成功隐藏子界面。</returns>
    public bool HideSubUIForm(int parentUIFormId, int subUIFormId)
    {
        if (parentUIFormId <= 0)
        {
            Logger.LogWarningFormat("Hide sub UI form failed: Parent UI form ID '{0}' is invalid.", parentUIFormId);
            return false;
        }

        if (subUIFormId <= 0)
        {
            Logger.LogWarningFormat("Hide sub UI form failed: Sub UI form ID '{0}' is invalid.", subUIFormId);
            return false;
        }

        IUIForm parentForm = GetUIFormById(parentUIFormId);
        if (parentForm == null)
        {
            Logger.LogWarningFormat("Hide sub UI form failed: Parent UI form with ID '{0}' is not found.", parentUIFormId);
            return false;
        }

        return HideSubUIForm(parentForm, subUIFormId);
    }

    /// <summary>
    /// 隐藏子界面（不销毁，只是隐藏）。
    /// </summary>
    /// <param name="parentUIForm">父界面。</param>
    /// <param name="subUIFormId">子界面ID。</param>
    /// <returns>是否成功隐藏子界面。</returns>
    public bool HideSubUIForm(IUIForm parentUIForm, int subUIFormId)
    {
        if (parentUIForm == null)
        {
            Logger.LogWarning("Hide sub UI form failed: Parent UI form is null.");
            return false;
        }

        if (subUIFormId <= 0)
        {
            Logger.LogWarningFormat("Hide sub UI form failed: Sub UI form ID '{0}' is invalid.", subUIFormId);
            return false;
        }

        UIForm parentForm = parentUIForm as UIForm;
        if (parentForm == null)
        {
            Logger.LogWarning("Hide sub UI form failed: Parent UI form is not a valid UIForm instance.");
            return false;
        }

        // 查找子界面
        IUIForm[] subForms = parentForm.SubUIForms;
        foreach (IUIForm subForm in subForms)
        {
            UIForm form = subForm as UIForm;
            if (form != null && form.UIFormId == subUIFormId)
            {
                // 隐藏子界面
                UIFormLogic logic = form.Logic;
                if (logic != null)
                {
                    logic.Visible = false;
                    logic.OnPause();
                    return true;
                }
            }
        }

        Logger.LogWarningFormat("Hide sub UI form failed: Sub UI form with ID '{0}' is not found in parent UI form.", subUIFormId);
        return false;
    }

    /// <summary>
    /// 显示所有子界面。
    /// </summary>
    /// <param name="parentUIFormId">父界面ID。</param>
    /// <returns>是否成功显示所有子界面。</returns>
    public bool ShowAllSubUIForms(int parentUIFormId)
    {
        if (parentUIFormId <= 0)
        {
            Logger.LogWarningFormat("Show all sub UI forms failed: Parent UI form ID '{0}' is invalid.", parentUIFormId);
            return false;
        }

        IUIForm parentForm = GetUIFormById(parentUIFormId);
        if (parentForm == null)
        {
            Logger.LogWarningFormat("Show all sub UI forms failed: Parent UI form with ID '{0}' is not found.", parentUIFormId);
            return false;
        }

        return ShowAllSubUIForms(parentForm);
    }

    /// <summary>
    /// 显示所有子界面。
    /// </summary>
    /// <param name="parentUIForm">父界面。</param>
    /// <returns>是否成功显示所有子界面。</returns>
    public bool ShowAllSubUIForms(IUIForm parentUIForm)
    {
        if (parentUIForm == null)
        {
            Logger.LogWarning("Show all sub UI forms failed: Parent UI form is null.");
            return false;
        }

        UIForm parentForm = parentUIForm as UIForm;
        if (parentForm == null)
        {
            Logger.LogWarning("Show all sub UI forms failed: Parent UI form is not a valid UIForm instance.");
            return false;
        }

        IUIForm[] subForms = parentForm.SubUIForms;
        if (subForms == null || subForms.Length == 0)
        {
            return true; // 没有子界面，返回成功
        }

        bool allSuccess = true;
        foreach (IUIForm subForm in subForms)
        {
            if (subForm != null)
            {
                UIFormLogic logic = (subForm as UIForm)?.Logic;
                if (logic != null)
                {
                    logic.Visible = true;
                    logic.OnResume();
                }
                else
                {
                    allSuccess = false;
                }
            }
        }

        return allSuccess;
    }

    /// <summary>
    /// 隐藏所有子界面。
    /// </summary>
    /// <param name="parentUIFormId">父界面ID。</param>
    /// <returns>是否成功隐藏所有子界面。</returns>
    public bool HideAllSubUIForms(int parentUIFormId)
    {
        if (parentUIFormId <= 0)
        {
            Logger.LogWarningFormat("Hide all sub UI forms failed: Parent UI form ID '{0}' is invalid.", parentUIFormId);
            return false;
        }

        IUIForm parentForm = GetUIFormById(parentUIFormId);
        if (parentForm == null)
        {
            Logger.LogWarningFormat("Hide all sub UI forms failed: Parent UI form with ID '{0}' is not found.", parentUIFormId);
            return false;
        }

        return HideAllSubUIForms(parentForm);
    }

    /// <summary>
    /// 隐藏所有子界面。
    /// </summary>
    /// <param name="parentUIForm">父界面。</param>
    /// <returns>是否成功隐藏所有子界面。</returns>
    public bool HideAllSubUIForms(IUIForm parentUIForm)
    {
        if (parentUIForm == null)
        {
            Logger.LogWarning("Hide all sub UI forms failed: Parent UI form is null.");
            return false;
        }

        UIForm parentForm = parentUIForm as UIForm;
        if (parentForm == null)
        {
            Logger.LogWarning("Hide all sub UI forms failed: Parent UI form is not a valid UIForm instance.");
            return false;
        }

        IUIForm[] subForms = parentForm.SubUIForms;
        if (subForms == null || subForms.Length == 0)
        {
            return true; // 没有子界面，返回成功
        }

        bool allSuccess = true;
        foreach (IUIForm subForm in subForms)
        {
            if (subForm != null)
            {
                UIFormLogic logic = (subForm as UIForm)?.Logic;
                if (logic != null)
                {
                    logic.Visible = false;
                    logic.OnPause();
                }
                else
                {
                    allSuccess = false;
                }
            }
        }

        return allSuccess;
    }

    #endregion
}

